<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 引入独立的 Header 组件-->
    <Header />
    <!-- 左侧导航栏 -->
    <aside
      class="fixed left-0 top-16 bottom-0 w-64 bg-gray-800 text-white z-10 overflow-y-auto"
    >
      <nav class="py-4">
        <div v-for="(menu, index) in mainMenus" :key="index" class="mb-1">
          <div
            class="flex items-center px-6 py-3 cursor-pointer hover:bg-gray-700"
            :class="{ 'bg-blue-700': menu.active }"
            @click="toggleMenu(index)"
          >
            <i :class="menu.icon + ' mr-3 w-5 text-center'"></i>
            <span>{{ menu.name }}</span>
            <i
              class="fas fa-chevron-down ml-auto text-xs transition-transform duration-200"
              :class="{ 'transform rotate-180': menu.expanded }"
            ></i>
          </div>
          <div v-if="menu.expanded" class="bg-gray-900">
            <div
              v-for="(submenu, subIndex) in menu.subMenus"
              :key="subIndex"
              class="flex items-center px-10 py-2 cursor-pointer hover:bg-gray-700"
              :class="{ 'text-blue-400': submenu.active }"
              @click="selectSubmenu(index, subIndex)"
            >
              <a
                v-if="submenu.link"
                :href="submenu.link"
                data-readdy="true"
                class="text-sm w-full"
                >{{ submenu.name }}</a
              >
              <span v-else class="text-sm">{{ submenu.name }}</span>
            </div>
          </div>
        </div>
      </nav>
    </aside>
    <!-- 主内容区域 -->
    <main class="pt-16 pl-64">
      <div class="container mx-auto p-6">
        <!-- 面包屑导航 -->
        <div class="flex items-center text-sm mb-4 text-gray-500">
          <span>首页</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span>系统管理</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <a href="#" class="text-blue-600">用户权限管理</a>
        </div>
        <!-- 数据统计卡片 -->
        <div class="grid grid-cols-4 gap-4 mb-6">
          <!-- 用户总数卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-4"
            >
              <i class="fas fa-users text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">用户总数</div>
              <div class="text-2xl font-bold text-gray-900">156</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 5.4%
              </div>
            </div>
          </div>
          <!-- 角色数量卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4"
            >
              <i class="fas fa-user-tag text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">角色数量</div>
              <div class="text-2xl font-bold text-gray-900">12</div>
              <div class="text-xs text-green-600 flex items-center">
                <i class="fas fa-arrow-up mr-1"></i> 环比增长 9.1%
              </div>
            </div>
          </div>
          <!-- 在线用户卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-4"
            >
              <i class="fas fa-user-check text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">在线用户</div>
              <div class="text-2xl font-bold text-gray-900">42</div>
              <div class="text-xs text-gray-500 flex items-center">
                <span>占比 26.9%</span>
              </div>
            </div>
          </div>
          <!-- 权限项卡片 -->
          <div class="bg-white rounded-lg shadow-sm p-4 flex items-center">
            <div
              class="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-600 mr-4"
            >
              <i class="fas fa-key text-xl"></i>
            </div>
            <div>
              <div class="text-sm text-gray-500">权限项</div>
              <div class="text-2xl font-bold text-gray-900">85</div>
              <div class="text-xs text-blue-600 flex items-center">
                <i class="fas fa-sync-alt mr-1"></i> 最近更新 3 天前
              </div>
            </div>
          </div>
        </div>

        <!-- 标签页切换 -->
        <div class="bg-white rounded-lg shadow-sm mb-6">
          <div class="border-b border-gray-200">
            <nav class="flex -mb-px">
              <button
                v-for="(tab, index) in tabs"
                :key="index"
                class="py-4 px-6 font-medium text-sm border-b-2 focus:outline-none !rounded-button whitespace-nowrap cursor-pointer"
                :class="
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                "
                @click="activeTab = tab.id"
              >
                <i :class="tab.icon + ' mr-2'"></i>
                {{ tab.name }}
              </button>
            </nav>
          </div>
          <!-- 用户管理标签页 -->
          <div v-if="activeTab === 'users'" class="p-4">
            <!-- 筛选条件区域-->
            <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
              <div class="flex flex-wrap items-center gap-4">
                <!-- 部门筛选 -->
                <div class="flex items-center">
                  <span class="text-gray-600 mr-2">部门：</span>
                  <div class="relative">
                    <button
                      class="flex items-center justify-between w-48 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors duration-150"
                      @click.stop="toggleDepartmentDropdown"
                    >
                      <span class="text-gray-700">{{
                        filterConditions.department
                      }}</span>
                      <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
                    </button>
                    <!-- 部门下拉菜单 -->
                    <div
                      v-if="showDepartmentDropdown"
                      class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                      @click.stop
                    >
                      <div
                        v-for="(dept, index) in departmentOptions"
                        :key="index"
                        class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm transition-colors duration-150"
                        :class="{
                          'bg-blue-50 text-blue-600':
                            filterConditions.department === dept,
                        }"
                        @click="selectDepartment(dept)"
                      >
                        {{ dept }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 角色筛选 -->
                <div class="flex items-center">
                  <span class="text-gray-600 mr-2">角色：</span>
                  <div class="relative">
                    <button
                      class="flex items-center justify-between w-48 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors duration-150"
                      @click.stop="toggleRoleDropdown"
                    >
                      <span class="text-gray-700">{{
                        filterConditions.role
                      }}</span>
                      <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
                    </button>
                    <!-- 角色下拉菜单 -->
                    <div
                      v-if="showRoleDropdown"
                      class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                      @click.stop
                    >
                      <div
                        v-for="(role, index) in roleOptions"
                        :key="index"
                        class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm transition-colors duration-150"
                        :class="{
                          'bg-blue-50 text-blue-600':
                            filterConditions.role === role,
                        }"
                        @click="selectRole(role)"
                      >
                        {{ role }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 状态筛选 -->
                <div class="flex items-center">
                  <span class="text-gray-600 mr-2">状态：</span>
                  <div class="relative">
                    <button
                      class="flex items-center justify-between w-48 px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer hover:bg-gray-200 transition-colors duration-150"
                      @click.stop="toggleStatusDropdown"
                    >
                      <span class="text-gray-700">{{
                        filterConditions.status
                      }}</span>
                      <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
                    </button>
                    <!-- 状态下拉菜单 -->
                    <div
                      v-if="showStatusDropdown"
                      class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                      @click.stop
                    >
                      <div
                        v-for="(status, index) in statusOptions"
                        :key="index"
                        class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm transition-colors duration-150"
                        :class="{
                          'bg-blue-50 text-blue-600':
                            filterConditions.status === status,
                        }"
                        @click="selectStatus(status)"
                      >
                        {{ status }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 搜索框 -->
                <div class="flex items-center ml-4">
                  <div class="relative">
                    <input
                      type="text"
                      v-model="filterConditions.search"
                      placeholder="搜索用户名/姓名/手机号"
                      class="w-64 pl-10 pr-4 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none focus:bg-white focus:ring-2 focus:ring-blue-500 transition-colors duration-150"
                      @input="handleSearch"
                    />
                    <i
                      class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                    ></i>
                  </div>
                </div>
                <div class="ml-auto">
                  <button
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer hover:bg-blue-700 transition-colors duration-150"
                    @click="addUser"
                  >
                    <i class="fas fa-user-plus mr-2"></i> 新建用户
                  </button>
                </div>
              </div>
            </div>
            <!-- 用户管理表格内容 -->
            <div class="overflow-x-auto">
              <table class="min-w-full divide-y divide-gray-200">
                <thead>
                  <tr>
                    <!-- 表格头部的复选框 -->
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                    >
                      <div class="flex items-center">
                        <input
                          type="checkbox"
                          class="mr-2"
                          @click="toggleSelectAll"
                          :checked="isAllSelected && paginatedUsers.length > 0"
                        />
                        <span class="flex-1 text-center">用户信息</span>
                      </div>
                    </th>
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                    >
                      所属部门
                    </th>
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                    >
                      角色
                    </th>
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                    >
                      状态
                    </th>
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                    >
                      最后登录时间
                    </th>
                    <th
                      class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                    >
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <!-- 分页功能修改 -->
                  <tr
                    v-for="(user, index) in paginatedUsers"
                    :key="index"
                    class="hover:bg-gray-50"
                    :class="{
                      'bg-blue-50':
                        currentSelectedUser &&
                        currentSelectedUser.id === user.id,
                    }"
                  >
                    <td class="px-4 py-3 text-center">
                      <div class="flex items-center">
                        <input
                          type="checkbox"
                          class="mr-2"
                          :checked="
                            currentSelectedUser &&
                            currentSelectedUser.id === user.id
                          "
                          @change="toggleSelectUser(user, $event)"
                        />

                        <div
                          class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center mr-3 text-gray-600"
                        >
                          <i
                            v-if="user.gender === '男'"
                            class="fas fa-male"
                          ></i>
                          <i
                            v-else-if="user.gender === '女'"
                            class="fas fa-female"
                          ></i>
                          <i v-else class="fas fa-user"></i>
                        </div>
                        <div>
                          <div class="text-sm font-medium text-gray-900">
                            {{ user.name }}
                          </div>
                          <div class="text-xs text-gray-500">
                            {{ user.username }}
                          </div>
                          <div class="text-xs text-gray-500">
                            {{ user.phone }}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div class="text-sm text-gray-900 justify-center">
                        {{ user.department }}
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div class="flex flex-wrap gap-1 justify-center">
                        <span
                          v-for="(role, roleIndex) in user.roles"
                          :key="roleIndex"
                          class="px-2 py-1 text-xs rounded-full"
                          :class="getRoleClass(role)"
                        >
                          {{ role }}
                        </span>
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div class="flex items-center justify-center">
                        <div
                          class="w-2 h-2 rounded-full mr-2"
                          :class="
                            user.status === '启用'
                              ? 'bg-green-500'
                              : 'bg-red-500'
                          "
                        ></div>
                        <span
                          class="text-sm"
                          :class="
                            user.status === '启用'
                              ? 'text-green-600'
                              : 'text-red-600'
                          "
                          >{{ user.status }}</span
                        >
                      </div>
                    </td>
                    <td class="px-4 py-3">
                      <div class="text-sm text-gray-900 justify-center">
                        {{ user.lastLogin }}
                      </div>
                    </td>
                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                      <div class="flex space-x-2 justify-center">
                        <button
                          class="text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer"
                          @click="editUser(user)"
                        >
                          <i class="fas fa-edit mr-1"></i> 编辑
                        </button>
                        <button
                          class="text-yellow-600 hover:text-yellow-800 !rounded-button whitespace-nowrap cursor-pointer"
                          @click="resetPassword(user)"
                        >
                          <i class="fas fa-key mr-1"></i> 重置密码
                        </button>
                        <button
                          class="hover:text-red-800 !rounded-button whitespace-nowrap cursor-pointer"
                          :class="
                            user.status === '启用'
                              ? 'text-red-600'
                              : 'text-green-600'
                          "
                          @click="toggleUserStatus(user)"
                        >
                          <i
                            :class="
                              user.status === '启用'
                                ? 'fas fa-ban mr-1'
                                : 'fas fa-check-circle mr-1'
                            "
                          ></i>
                          {{ user.status === "启用" ? "禁用" : "启用" }}
                        </button>
                      </div>
                    </td>
                  </tr>
                  <!-- 添加空状态提示 -->
                  <tr v-if="paginatedUsers.length === 0">
                    <td colspan="6" class="px-4 py-8 text-center">
                      <div
                        class="flex flex-col items-center justify-center text-gray-500"
                      >
                        <i
                          class="fas fa-search text-4xl mb-4 text-gray-300"
                        ></i>
                        <p class="text-lg mb-2">没有找到匹配的用户</p>
                        <p class="text-sm">请尝试调整筛选条件</p>
                        <div class="mt-4 text-xs text-gray-400">
                          当前筛选条件：
                          <span
                            v-if="filterConditions.department !== '全部部门'"
                            >部门：{{ filterConditions.department }}</span
                          >
                          <span v-if="filterConditions.role !== '全部角色'"
                            >，角色：{{ filterConditions.role }}</span
                          >
                          <span v-if="filterConditions.status !== '全部状态'"
                            >，状态：{{ filterConditions.status }}</span
                          >
                          <span v-if="filterConditions.search"
                            >，搜索：{{ filterConditions.search }}</span
                          >
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
              <!-- 批量操作和分页功能 -->
              <div class="flex justify-between items-center mt-4 px-4 py-3">
                <div class="flex items-center space-x-2">
                  <button
                    class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    :disabled="!hasSelected"
                    :class="{ 'opacity-50 cursor-not-allowed': !hasSelected }"
                    @click="batchDelete"
                  >
                    批量删除
                  </button>
                  <button
                    class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    :disabled="!hasSelected"
                    :class="{ 'opacity-50 cursor-not-allowed': !hasSelected }"
                    @click="batchExport"
                  >
                    批量导出
                  </button>
                  <!-- 显示多选状态 -->
                  <span class="text-sm text-gray-500 ml-2" v-if="hasSelected">
                    已选择
                    <span class="text-blue-600">{{ selectedCount }}</span> 项
                    <span v-if="selectedCount <= 3" class="text-blue-600 ml-2">
                      ({{ selectedUsers.map((user) => user.name).join(", ") }})
                    </span>
                    <span v-else class="text-blue-600 ml-2">
                      ({{
                        selectedUsers
                          .slice(0, 3)
                          .map((user) => user.name)
                          .join(", ")
                      }}等{{ selectedCount }}个用户)
                    </span>
                  </span>
                </div>
                <div class="flex items-center">
                  <span class="text-sm text-gray-500 mr-2">每页显示：</span>
                  <select
                    v-model="pageSize"
                    @change="changePageSize(parseInt($event.target.value))"
                    class="px-2 py-1 bg-gray-100 border border-gray-300 rounded text-sm focus:outline-none"
                  >
                    <option v-for="size in pageSizes" :key="size" :value="size">
                      {{ size }} 条
                    </option>
                  </select>
                </div>
              </div>
              <div class="flex justify-between items-center mt-4">
                <div class="flex items-center">
                  <span class="text-sm text-gray-500"
                    >共 {{ filteredUsers.length }} 条记录</span
                  >
                </div>
                <div class="flex items-center space-x-2">
                  <button
                    @click="changePage(currentPage - 1)"
                    :disabled="currentPage === 1"
                    class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    :class="{
                      'opacity-50 cursor-not-allowed': currentPage === 1,
                    }"
                  >
                    上一页
                  </button>

                  <!-- 动态生成页码按钮 -->
                  <button
                    v-for="page in totalPages"
                    :key="page"
                    @click="changePage(page)"
                    class="px-3 py-1 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    :class="
                      currentPage === page
                        ? 'bg-blue-600 text-white'
                        : 'bg-gray-100 text-gray-700'
                    "
                  >
                    {{ page }}
                  </button>

                  <button
                    @click="changePage(currentPage + 1)"
                    :disabled="currentPage === totalPages"
                    class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    :class="{
                      'opacity-50 cursor-not-allowed':
                        currentPage === totalPages,
                    }"
                  >
                    下一页
                  </button>
                  <span class="text-sm text-gray-500 ml-2"
                    >第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 角色管理标签页 -->
        <div v-if="activeTab === 'roles'" class="p-4">
          <!-- 添加角色管理的筛选条件 -->
          <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-wrap items-center gap-4">
              <!-- 角色搜索框 -->
              <div class="flex items-center">
                <div class="relative">
                  <input
                    type="text"
                    v-model="roleFilterConditions.search"
                    placeholder="搜索角色名称/标识/描述"
                    class="w-64 pl-10 pr-4 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none focus:bg-white focus:ring-2 focus:ring-blue-500 transition-colors duration-150"
                    @input="handleRoleSearch"
                  />
                  <i
                    class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                  ></i>
                </div>
              </div>

              <div class="ml-auto">
                <button
                  class="px-4 py-2 bg-blue-600 text-white rounded-lg flex items-center !rounded-button whitespace-nowrap cursor-pointer"
                  @click="addRole"
                >
                  <i class="fas fa-plus mr-2"></i> 新建角色
                </button>
              </div>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead>
                <tr>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    角色名称
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    角色描述
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    创建时间
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider text-left"
                  >
                    用户数量
                  </th>
                  <th
                    class="px-4 py-3 bg-gray-50 text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    操作
                  </th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr
                  v-for="(role, index) in paginatedRoles"
                  :key="index"
                  class="hover:bg-gray-50"
                >
                  <td class="px-4 py-3">
                    <div class="flex items-center">
                      <div
                        class="w-8 h-8 rounded-full flex items-center justify-center mr-3"
                        :class="role.iconBg"
                      >
                        <i :class="role.icon + ' ' + role.iconColor"></i>
                      </div>
                      <div class="text-sm font-medium text-gray-900">
                        {{ role.name }}
                      </div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ role.description }}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ role.createTime }}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="text-sm text-gray-900 justify-center">
                      {{ role.userCount }}
                    </div>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2 justify-center">
                      <button
                        class="text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="editRole(role)"
                      >
                        <i class="fas fa-edit mr-1"></i> 编辑
                      </button>
                      <button
                        class="text-purple-600 hover:text-purple-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="configPermission(role)"
                      >
                        <i class="fas fa-key mr-1"></i> 权限设置
                      </button>
                      <button
                        class="text-red-600 hover:text-red-800 !rounded-button whitespace-nowrap cursor-pointer"
                        @click="deleteRole(role)"
                      >
                        <i class="fas fa-trash-alt mr-1"></i> 删除
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            <!-- 添加角色列表的空状态提示 -->
            <div
              v-if="paginatedRoles.length === 0"
              class="text-center py-8 text-gray-500"
            >
              <i class="fas fa-search text-4xl mb-4 text-gray-300"></i>
              <p>没有找到匹配的角色</p>
              <p class="text-sm mt-2">请尝试调整搜索条件</p>
            </div>
          </div>
        </div>
        <!-- 权限配置标签页 -->
        <div v-if="activeTab === 'permissions'" class="p-4">
          <div class="flex h-[600px]">
            <!-- 左侧模块树 -->
            <div class="w-1/4 border-r border-gray-200 pr-4 overflow-y-auto">
              <div class="mb-4">
                <div class="text-lg font-medium mb-2">权限模块</div>
                <div class="relative">
                  <input
                    type="text"
                    v-model="moduleSearchKeyword"
                    placeholder="搜索模块名称"
                    class="w-80 pl-10 pr-4 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none focus:bg-white focus:ring-2 focus:ring-blue-500 transition-colors duration-150"
                  />
                  <i
                    class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                  ></i>
                </div>
              </div>
              <div class="permission-tree">
                <div
                  v-for="(module, index) in filteredPermissionModules"
                  :key="index"
                  class="mb-2"
                >
                  <div
                    class="flex items-center p-2 rounded hover:bg-gray-100 cursor-pointer transition-colors duration-200"
                    :class="{
                      'bg-blue-50 text-blue-600': module.id === selectedModule,
                      'bg-gray-50': module.expanded,
                    }"
                    @click="toggleModule(module.id)"
                  >
                    <i
                      :class="
                        module.expanded
                          ? 'fas fa-folder-open mr-2 text-yellow-500'
                          : 'fas fa-folder mr-2 text-yellow-500'
                      "
                    ></i>
                    <span class="font-medium">{{ module.name }}</span>
                    <i
                      :class="
                        module.expanded
                          ? 'fas fa-chevron-down text-gray-500'
                          : 'fas fa-chevron-right text-gray-500'
                      "
                      class="transition-transform duration-200"
                    ></i>
                  </div>
                  <!-- 子模块列表，根据展开状态显示 -->
                  <div
                    v-if="module.expanded && module.children"
                    class="ml-4 mt-1 transition-all duration-300 ease-in-out"
                    :class="
                      module.expanded
                        ? 'max-h-96 opacity-100'
                        : 'max-h-0 opacity-0'
                    "
                  >
                    <div
                      v-for="(submodule, subIndex) in module.children"
                      :key="subIndex"
                      class="flex items-center p-2 rounded hover:bg-gray-100 cursor-pointer transition-colors duration-200 mb-1"
                      :class="{
                        'bg-blue-50 text-blue-600':
                          submodule.id === selectedModule,
                      }"
                      @click.stop="selectModule(submodule.id)"
                    >
                      <i class="fas fa-list-alt mr-2 text-blue-500 text-sm"></i>
                      <span class="text-sm">{{ submodule.name }}</span>
                    </div>
                  </div>
                </div>

                <!-- 空状态提示 -->
                <div
                  v-if="
                    filteredPermissionModules.length === 0 &&
                    moduleSearchKeyword
                  "
                  class="text-center py-8 text-gray-500"
                >
                  <i class="fas fa-search text-4xl mb-4 text-gray-300"></i>
                  <p>没有找到匹配的模块</p>
                  <p class="text-sm mt-2">请尝试调整搜索关键词</p>
                </div>
              </div>
            </div>

            <!-- 右侧权限点列表 -->
            <div class="w-3/4 pl-4 overflow-y-auto">
              <div class="mb-4 flex justify-between items-center">
                <div class="text-lg font-medium">
                  {{ currentModuleName }} 权限点列表
                  <span
                    v-if="moduleSearchKeyword"
                    class="text-sm text-blue-600 ml-2"
                  >
                    (搜索: "{{ moduleSearchKeyword }}")
                  </span>
                </div>
                <div class="flex items-center space-x-2">
                  <button
                    class="px-3 py-1 bg-blue-600 text-white rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    @click="selectAllPermissions"
                  >
                    全选
                  </button>
                  <button
                    class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                    @click="deselectAllPermissions"
                  >
                    取消全选
                  </button>
                </div>
              </div>
              <div class="bg-gray-50 p-4 rounded-lg mb-4">
                <div class="flex items-center mb-2">
                  <div
                    class="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-2"
                  >
                    <i class="fas fa-info-circle"></i>
                  </div>
                  <div class="text-sm text-gray-700">
                    当前正在配置
                    <span class="text-blue-600 font-medium">{{
                      currentModuleName
                    }}</span>
                    模块的权限，共 {{ currentPermissions.length }} 个权限点
                    <span
                      v-if="selectedPermissionsCount > 0"
                      class="text-green-600 font-medium"
                    >
                      (已选中 {{ selectedPermissionsCount }} 个)
                    </span>
                  </div>
                </div>
              </div>
              <div class="grid grid-cols-2 gap-4">
                <div
                  v-for="(permission, index) in currentPermissions"
                  :key="index"
                  class="bg-white p-3 rounded-lg border border-gray-200 hover:shadow-sm"
                >
                  <div class="flex items-center">
                    <input
                      type="checkbox"
                      v-model="permission.selected"
                      class="mr-3"
                    />
                    <div>
                      <div class="text-sm font-medium text-gray-900">
                        {{ permission.name }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ permission.description }}
                      </div>
                      <div class="text-xs text-gray-400 mt-1">
                        权限标识：{{ permission.key }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex justify-end mt-6 space-x-3">
                <button
                  class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
                  @click="resetPermissions"
                >
                  重置
                </button>
                <button
                  class="px-4 py-2 bg-blue-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
                  @click="savePermissionConfig"
                >
                  保存配置
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <!-- 新建用户弹窗 -->
    <div
      v-if="showAddUserModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
      @click="
        showAddUserModal = false;
        showDepartmentDropdown = false;
      "
    >
      <div
        class="bg-white rounded-lg p-6 w-[600px] max-h-[90vh] overflow-y-auto"
        @click.stop
      >
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800">
            {{ editingUser ? "编辑用户" : "新建用户" }}
          </h3>
          <button
            @click="showAddUserModal = false"
            class="text-gray-500 hover:text-gray-700 cursor-pointer"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="grid grid-cols-2 gap-4 mb-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >用户名</label
            >
            <input
              type="text"
              v-model="userForm.username"
              placeholder="请输入用户名"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >真实姓名</label
            >
            <input
              type="text"
              v-model="userForm.name"
              placeholder="请输入真实姓名"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >手机号</label
            >
            <input
              type="text"
              v-model="userForm.phone"
              placeholder="请输入手机号"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >邮箱</label
            >
            <input
              type="email"
              v-model="userForm.email"
              placeholder="请输入邮箱"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >所属部门</label
            >
            <div class="relative">
              <button
                type="button"
                class="flex items-center justify-between w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg focus:outline-none !rounded-button whitespace-nowrap cursor-pointer"
                @click="
                  showUserFormDepartmentDropdown =
                    !showUserFormDepartmentDropdown
                "
              >
                <span class="text-gray-700">{{
                  userForm.department || "请选择部门"
                }}</span>
                <i class="fas fa-chevron-down text-gray-500 text-xs"></i>
              </button>
              <!-- 部门下拉菜单 -->
              <div
                v-if="showUserFormDepartmentDropdown"
                class="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
              >
                <div
                  v-for="(dept, index) in departments"
                  :key="index"
                  class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm"
                  @click="selectUserFormDepartment(dept)"
                >
                  {{ dept }}
                </div>
              </div>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >性别</label
            >
            <div class="flex space-x-4 mt-2">
              <label class="flex items-center">
                <input
                  type="radio"
                  name="gender"
                  value="男"
                  v-model="userForm.gender"
                  class="mr-2"
                />
                <span class="text-sm text-gray-700">男</span>
              </label>
              <label class="flex items-center">
                <input
                  type="radio"
                  name="gender"
                  value="女"
                  v-model="userForm.gender"
                  class="mr-2"
                />
                <span class="text-sm text-gray-700">女</span>
              </label>
            </div>
          </div>
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >角色分配</label
          >
          <div class="bg-gray-50 p-3 rounded-lg border border-gray-200">
            <div class="flex flex-wrap gap-2">
              <div
                v-for="(role, index) in availableRoles"
                :key="index"
                class="flex items-center px-3 py-1 rounded-full border cursor-pointer"
                :class="
                  userForm.roles.includes(role)
                    ? 'bg-blue-50 border-blue-300 text-blue-700'
                    : 'bg-white border-gray-300 text-gray-700'
                "
                @click="toggleRole(role)"
              >
                <span class="text-sm">{{ role }}</span>
                <i
                  v-if="userForm.roles.includes(role)"
                  class="fas fa-check ml-1 text-xs"
                ></i>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!editingUser" class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >密码</label
          >
          <input
            type="password"
            v-model="userForm.password"
            placeholder="请输入密码"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
          />
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >状态</label
          >
          <div class="flex space-x-4 mt-2">
            <label class="flex items-center">
              <input
                type="radio"
                name="status"
                value="启用"
                v-model="userForm.status"
                class="mr-2"
              />
              <span class="text-sm text-gray-700">启用</span>
            </label>
            <label class="flex items-center">
              <input
                type="radio"
                name="status"
                value="禁用"
                v-model="userForm.status"
                class="mr-2"
              />
              <span class="text-sm text-gray-700">禁用</span>
            </label>
          </div>
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >备注</label
          >
          <textarea
            v-model="userForm.remark"
            placeholder="请输入备注信息"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            rows="3"
          ></textarea>
        </div>
        <div class="flex justify-end space-x-3">
          <button
            @click="showAddUserModal = false"
            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
            @click="saveUser"
          >
            确认
          </button>
        </div>
      </div>
    </div>
    <!-- 新建角色弹窗 -->
    <div
      v-if="showAddRoleModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg p-6 w-[500px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800">
            {{ editingRole ? "编辑角色" : "新建角色" }}
          </h3>
          <button
            @click="showAddRoleModal = false"
            class="text-gray-500 hover:text-gray-700 cursor-pointer"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >角色名称</label
          >
          <input
            type="text"
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
          />
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >角色标识</label
          >
          <input
            type="text"
            v-model="roleForm.key"
            placeholder="请输入角色标识"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
          />
          <div class="text-xs text-gray-500 mt-1">
            角色标识用于系统内部识别，建议使用英文
          </div>
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >角色描述</label
          >
          <textarea
            v-model="roleForm.description"
            placeholder="请输入角色描述"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            rows="3"
          ></textarea>
        </div>
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1"
            >角色排序</label
          >
          <input
            type="number"
            v-model="roleForm.sort"
            placeholder="请输入排序数字"
            class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
          />
          <div class="text-xs text-gray-500 mt-1">数字越小越靠前</div>
        </div>
        <div class="flex justify-end space-x-3">
          <button
            @click="showAddRoleModal = false"
            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
            @click="saveRole"
          >
            确认
          </button>
        </div>
      </div>
    </div>
    <!-- 权限设置弹窗 -->
    <div
      v-if="showPermissionModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div
        class="bg-white rounded-lg p-6 w-[800px] max-h-[90vh] overflow-y-auto"
      >
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800">
            权限设置 - {{ currentRole.name }}
          </h3>
          <button
            @click="showPermissionModal = false"
            class="text-gray-500 hover:text-gray-700 cursor-pointer"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="bg-blue-50 p-4 rounded-lg mb-4">
          <div class="flex items-center">
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center mr-3"
              :class="currentRole.iconBg"
            >
              <i :class="currentRole.icon + ' ' + currentRole.iconColor"></i>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-900">
                {{ currentRole.name }}
              </div>
              <div class="text-xs text-gray-500">
                {{ currentRole.description }}
              </div>
            </div>
            <div class="ml-auto">
              <div class="text-sm text-gray-500">
                用户数量：<span class="text-blue-600 font-medium">{{
                  currentRole.userCount
                }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="mb-4">
          <div class="flex justify-between items-center mb-2">
            <div class="text-sm font-medium text-gray-700">权限配置</div>
            <div class="flex items-center space-x-2">
              <button
                class="px-3 py-1 bg-blue-600 text-white rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                @click="expandAllModules"
              >
                展开全部
              </button>
              <button
                class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm !rounded-button whitespace-nowrap cursor-pointer"
                @click="collapseAllModules"
              >
                收起全部
              </button>
            </div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
            <div
              v-for="(module, index) in permissionTree"
              :key="index"
              class="mb-4"
            >
              <div
                class="flex items-center p-2 bg-white rounded-lg shadow-sm mb-2"
              >
                <input
                  type="checkbox"
                  v-model="module.selected"
                  @change="selectModulePermissions(index)"
                  class="mr-3"
                />
                <i :class="module.icon + ' mr-2 ' + module.iconColor"></i>
                <span class="text-sm font-medium">{{ module.name }}</span>
                <i
                  :class="
                    module.expanded
                      ? 'fas fa-chevron-down ml-auto'
                      : 'fas fa-chevron-right ml-auto'
                  "
                  @click="togglePermissionModule(index)"
                  class="cursor-pointer text-gray-500"
                ></i>
              </div>
              <div v-if="module.expanded" class="ml-6 space-y-2">
                <div
                  v-for="(permission, pIndex) in module.permissions"
                  :key="pIndex"
                  class="flex items-center p-2 bg-white rounded-lg"
                >
                  <input
                    type="checkbox"
                    v-model="permission.selected"
                    @change="updateModuleSelection(index)"
                    class="mr-3"
                  />
                  <span class="text-sm">{{ permission.name }}</span>
                  <span class="text-xs text-gray-500 ml-2">{{
                    permission.description
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex justify-end space-x-3">
          <button
            @click="showPermissionModal = false"
            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
            @click="savePermissions"
          >
            保存
          </button>
        </div>
      </div>
    </div>
    <!-- 重置密码弹窗 -->
    <div
      v-if="showResetPasswordModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg p-6 w-[400px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800">重置密码</h3>
          <button
            @click="showResetPasswordModal = false"
            class="text-gray-500 hover:text-gray-700 cursor-pointer"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="mb-4">
          <div class="flex items-center mb-4">
            <div
              class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center mr-3 text-gray-600"
            >
              <i
                :class="
                  currentUser.gender === '男'
                    ? 'fas fa-male'
                    : currentUser.gender === '女'
                    ? 'fas fa-female'
                    : 'fas fa-user'
                "
              ></i>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-900">
                {{ currentUser.name }}
              </div>
              <div class="text-xs text-gray-500">
                {{ currentUser.username }}
              </div>
            </div>
          </div>
          <div class="bg-yellow-50 p-3 rounded-lg text-sm text-yellow-800 mb-4">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            重置密码后，该用户下次登录需要使用新密码
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >新密码</label
            >
            <input
              type="password"
              v-model="newPassword"
              placeholder="请输入新密码"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"
              >确认密码</label
            >
            <input
              type="password"
              v-model="confirmPassword"
              placeholder="请再次输入新密码"
              class="w-full px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm focus:outline-none border-none"
            />
          </div>
        </div>
        <div class="flex justify-end space-x-3">
          <button
            @click="showResetPasswordModal = false"
            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
            @click="confirmResetPassword"
          >
            确认重置
          </button>
        </div>
      </div>
    </div>
    <!-- 确认删除角色弹窗 -->
    <div
      v-if="showDeleteRoleModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg p-6 w-[400px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800">删除角色</h3>
          <button
            @click="showDeleteRoleModal = false"
            class="text-gray-500 hover:text-gray-700 cursor-pointer"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="mb-6">
          <div class="flex items-center mb-4">
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center mr-3"
              :class="currentRole.iconBg"
            >
              <i :class="currentRole.icon + ' ' + currentRole.iconColor"></i>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-900">
                {{ currentRole.name }}
              </div>
              <div class="text-xs text-gray-500">
                {{ currentRole.description }}
              </div>
            </div>
          </div>
          <div class="bg-red-50 p-3 rounded-lg text-sm text-red-800">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            确定要删除该角色吗？删除后将无法恢复，且该角色下的所有用户将失去此角色权限。
          </div>
          <div
            v-if="currentRole.userCount > 0"
            class="mt-3 text-sm text-gray-700"
          >
            当前有
            <span class="text-red-600 font-medium">{{
              currentRole.userCount
            }}</span>
            个用户关联了此角色
          </div>
        </div>
        <div class="flex justify-end space-x-3">
          <button
            @click="showDeleteRoleModal = false"
            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-red-600 text-white rounded-lg !rounded-button whitespace-nowrap cursor-pointer"
            @click="confirmDeleteRole"
          >
            确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
// 导入 Header 组件
import Header from "../components/Header.vue";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
  name: "UserManagement",
  components: {
    Header,
  },
  data() {
    return {
      // 添加单选相关数据
      selectedUserIds: [], // 存储选中的用户ID
      currentSelectedUser: null, // 当前选中的单个用户
      isAllSelected: false,
      // 权限模块搜索相关数据
      moduleSearchKeyword: "",
      // 分页相关数据
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5, 8],
      // 在data中添加部门数据和用户ID计数器
      departments: [
        "信息技术部",
        "安全生产部",
        "生产运营部",
        "质量管理部",
        "人力资源部",
        "财务部",
        "市场部",
        "研发部",
      ],
      // 添加下拉菜单显示状态
      showDepartmentDropdown: false,
      showRoleDropdown: false,
      showStatusDropdown: false,
      // 添加选项数据
      departmentOptions: [
        "全部部门",
        "信息技术部",
        "安全生产部",
        "生产运营部",
        "质量管理部",
        "人力资源部",
        "财务部",
        "市场部",
        "研发部",
      ],
      roleOptions: [
        "全部角色",
        "系统管理员",
        "部门管理员",
        "普通用户",
        "访客",
        "审计员",
        "安全员",
        "运维人员",
        "数据分析师",
      ],
      // 添加筛选条件相关数据
      filterConditions: {
        department: "全部部门",
        role: "全部角色",
        status: "全部状态",
        search: "",
      },
      // 添加角色管理的筛选条件
      roleFilterConditions: {
        search: "",
      },
      // 添加筛选后的用户数据
      filteredUsers: [],
      // 添加筛选后的角色数据
      filteredRoles: [],
      showUserFormDepartmentDropdown: false,
      statusOptions: ["全部状态", "启用", "禁用"],
      // 从本地存储加载下一个用户ID，如果没有则从9开始
      nextUserId:
        parseInt(localStorage.getItem("userManagementNextUserId")) || 9,
      activeTab: "users",
      tabs: [
        { id: "users", name: "用户管理", icon: "fas fa-users" },
        { id: "roles", name: "角色管理", icon: "fas fa-user-tag" },
        { id: "permissions", name: "权限配置", icon: "fas fa-key" },
      ],
      isAllSelected: false,
      // totalUsers: 156,
      showAddUserModal: false,
      showAddRoleModal: false,
      showPermissionModal: false,
      showResetPasswordModal: false,
      showDeleteRoleModal: false,
      editingUser: false,
      editingRole: false,
      currentUser: {},
      currentRole: {},
      newPassword: "",
      confirmPassword: "",
      userForm: {
        username: "",
        name: "",
        phone: "",
        email: "",
        department: "",
        gender: "男",
        roles: [],
        status: "启用",
        remark: "",
        password: "",
      },
      roleForm: {
        name: "",
        key: "",
        description: "",
        sort: 0,
      },
      availableRoles: [
        "系统管理员",
        "部门管理员",
        "普通用户",
        "访客",
        "审计员",
        "安全员",
        "运维人员",
        "数据分析师",
      ],
      selectedModule: "user",
      mainMenus: [
        {
          name: "监测报警",
          icon: "fas fa-bell",
          expanded: false,
          active: false,
          subMenus: [
            { name: "数据汇聚功能", active: false, link: "/data-aggregation" },
            {
              name: "监测指标统计",
              active: false,
              link: "/monitoring-indicators",
            },
            { name: "区域化展示", active: false, link: "/regional-display" },
          ],
        },
        {
          name: "风险研判",
          icon: "fas fa-exclamation-triangle",
          expanded: false,
          active: false,
          subMenus: [
             { name: '智能风险评估', active: false, link: '/intelligent-risk-assessment' },
                        { name: '预警信息推送', active: false, link: '/risk-warning-push' },
                        { name: '风险管理与分析', active: true, link: '/risk-analysis' },
                    ]
        },
        {
          name: "在线巡查",
          icon: "fas fa-search",
          expanded: false,
          active: false,
          subMenus: [
            {
              name: "企业信息汇总",
              active: false,
              link: "/summary-information",
            },
            { name: "巡查功能", active: false, link: "/patrol" },
            { name: "检索功能", active: false, link: "search" },
            { name: "一屏汇聚展示", active: false, link: "/screen-display" },
          ],
        },
        {
          name: "综合分析",
          icon: "fas fa-chart-line",
          expanded: false,
          active: false,
          subMenus: [
            { name: "联网与设备分析", active: false, link: "/equipment" },
            { name: "应用情况分析", active: false, link: "/application" },
            { name: "数据质量分析", active: false, link: "/data-quality" },
            { name: "定期专题报告", active: false, link: "report" },
          ],
        },
        {
          name: "系统管理",
          icon: "fas fa-cog",
          expanded: true,
          active: true,
          subMenus: [
            { name: "用户权限管理", active: true, link: "user-permission" },
            { name: "系统配置管理", active: false, link: "system-manage" },
            { name: "数据管理", active: false, link: "data-manage" },
            { name: "系统监控与维护", active: false, link: "monitoring" },
          ],
        },
      ],
      //从本地存储加载用户数据，如果没有则使用默认数据
      users: JSON.parse(localStorage.getItem("userManagementUsers")) || [
        {
          id: 1,
          username: "admin",
          name: "张三",
          phone: "13800138001",
          email: "zhangsan@example.com",
          department: "信息技术部",
          gender: "男",
          roles: ["系统管理员"],
          status: "启用",
          lastLogin: "2025-07-08 10:25:36",
          selected: false,
        },
        {
          id: 2,
          username: "lisi",
          name: "李四",
          phone: "13800138002",
          email: "lisi@example.com",
          department: "安全生产部",
          gender: "男",
          roles: ["部门管理员", "安全员"],
          status: "启用",
          lastLogin: "2025-07-08 09:15:22",
          selected: false,
        },
        {
          id: 3,
          username: "wangwu",
          name: "王五",
          phone: "13800138003",
          email: "wangwu@example.com",
          department: "生产运营部",
          gender: "男",
          roles: ["普通用户"],
          status: "启用",
          lastLogin: "2025-07-07 16:42:18",
          selected: false,
        },
        {
          id: 4,
          username: "zhaoliu",
          name: "赵六",
          phone: "13800138004",
          email: "zhaoliu@example.com",
          department: "质量管理部",
          gender: "男",
          roles: ["部门管理员"],
          status: "启用",
          lastLogin: "2025-07-07 14:30:45",
          selected: false,
        },
        {
          id: 5,
          username: "sunqi",
          name: "孙七",
          phone: "13800138005",
          email: "sunqi@example.com",
          department: "人力资源部",
          gender: "女",
          roles: ["普通用户"],
          status: "禁用",
          lastLogin: "2025-07-06 11:20:33",
          selected: false,
        },
        {
          id: 6,
          username: "zhouba",
          name: "周八",
          phone: "13800138006",
          email: "zhouba@example.com",
          department: "财务部",
          gender: "女",
          roles: ["部门管理员", "审计员"],
          status: "启用",
          lastLogin: "2025-07-08 08:55:19",
          selected: false,
        },
        {
          id: 7,
          username: "wujiu",
          name: "吴九",
          phone: "13800138007",
          email: "wujiu@example.com",
          department: "市场部",
          gender: "男",
          roles: ["普通用户"],
          status: "启用",
          lastLogin: "2025-07-07 17:10:42",
          selected: false,
        },
        {
          id: 8,
          username: "zhengshi",
          name: "郑十",
          phone: "13800138008",
          email: "zhengshi@example.com",
          department: "研发部",
          gender: "男",
          roles: ["数据分析师", "运维人员"],
          status: "启用",
          lastLogin: "2025-07-08 11:05:27",
          selected: false,
        },
      ],
      roles: JSON.parse(localStorage.getItem("userManagementRoles")) || [
        {
          id: 1,
          name: "系统管理员",
          key: "admin",
          description: "系统最高权限，可以管理所有功能和数据",
          createTime: "2025-01-15 10:00:00",
          userCount: 1,
          icon: "fas fa-user-shield",
          iconBg: "bg-red-100",
          iconColor: "text-red-600",
        },
        {
          id: 2,
          name: "部门管理员",
          key: "dept_admin",
          description: "可以管理本部门的用户和数据",
          createTime: "2025-01-15 10:05:00",
          userCount: 3,
          icon: "fas fa-users-cog",
          iconBg: "bg-blue-100",
          iconColor: "text-blue-600",
        },
        {
          id: 3,
          name: "普通用户",
          key: "user",
          description: "基础功能的使用权限",
          createTime: "2025-01-15 10:10:00",
          userCount: 3,
          icon: "fas fa-user",
          iconBg: "bg-green-100",
          iconColor: "text-green-600",
        },
        {
          id: 4,
          name: "访客",
          key: "guest",
          description: "仅有查看权限，无操作权限",
          createTime: "2025-01-15 10:15:00",
          userCount: 0,
          icon: "fas fa-user-clock",
          iconBg: "bg-gray-100",
          iconColor: "text-gray-600",
        },
        {
          id: 5,
          name: "审计员",
          key: "auditor",
          description: "负责系统操作审计和合规检查",
          createTime: "2025-02-20 14:30:00",
          userCount: 1,
          icon: "fas fa-user-tie",
          iconBg: "bg-purple-100",
          iconColor: "text-purple-600",
        },
        {
          id: 6,
          name: "安全员",
          key: "security",
          description: "负责安全生产相关工作",
          createTime: "2025-03-10 09:45:00",
          userCount: 1,
          icon: "fas fa-hard-hat",
          iconBg: "bg-yellow-100",
          iconColor: "text-yellow-600",
        },
        {
          id: 7,
          name: "运维人员",
          key: "ops",
          description: "负责系统运维和监控",
          createTime: "2025-04-05 11:20:00",
          userCount: 1,
          icon: "fas fa-tools",
          iconBg: "bg-indigo-100",
          iconColor: "text-indigo-600",
        },
        {
          id: 8,
          name: "数据分析师",
          key: "analyst",
          description: "负责数据分析和报表生成",
          createTime: "2025-05-12 15:40:00",
          userCount: 1,
          icon: "fas fa-chart-pie",
          iconBg: "bg-teal-100",
          iconColor: "text-teal-600",
        },
      ],
      // 添加角色ID计数器
      nextRoleId:
        parseInt(localStorage.getItem("userManagementNextRoleId")) || 9,
      permissionModules: [
        {
          id: "system",
          name: "系统管理",
          icon: "fas fa-cog",
          expanded: true,
          children: [
            { id: "user", name: "用户管理" },
            { id: "role", name: "角色管理" },
            { id: "permission", name: "权限管理" },
            { id: "menu", name: "菜单管理" },
            { id: "dept", name: "部门管理" },
          ],
        },
        {
          id: "monitor",
          name: "系统监控",
          icon: "fas fa-desktop",
          expanded: false,
          children: [
            { id: "online", name: "在线用户" },
            { id: "job", name: "定时任务" },
            { id: "server", name: "服务器监控" },
            { id: "cache", name: "缓存监控" },
          ],
        },
        {
          id: "log",
          name: "日志管理",
          icon: "fas fa-clipboard-list",
          expanded: false,
          children: [
            { id: "operlog", name: "操作日志" },
            { id: "loginlog", name: "登录日志" },
          ],
        },
        {
          id: "config",
          name: "系统配置",
          icon: "fas fa-wrench",
          expanded: false,
          children: [
            { id: "dict", name: "字典管理" },
            { id: "param", name: "参数设置" },
          ],
        },
        {
          id: "tool",
          name: "系统工具",
          icon: "fas fa-tools",
          expanded: false,
          children: [
            { id: "build", name: "表单构建" },
            { id: "gen", name: "代码生成" },
            { id: "interface", name: "系统接口" },
          ],
        },
      ],
      permissionTree: [
        {
          id: "system",
          name: "系统管理",
          icon: "fas fa-cog",
          iconColor: "text-blue-600",
          expanded: true,
          selected: true,
          permissions: [
            {
              id: 1,
              name: "用户查询",
              description: "查询用户列表",
              selected: true,
            },
            {
              id: 2,
              name: "用户新增",
              description: "新增用户",
              selected: true,
            },
            {
              id: 3,
              name: "用户修改",
              description: "修改用户信息",
              selected: true,
            },
            {
              id: 4,
              name: "用户删除",
              description: "删除用户",
              selected: true,
            },
            {
              id: 5,
              name: "角色查询",
              description: "查询角色列表",
              selected: true,
            },
            {
              id: 6,
              name: "角色新增",
              description: "新增角色",
              selected: true,
            },
            {
              id: 7,
              name: "角色修改",
              description: "修改角色信息",
              selected: true,
            },
            {
              id: 8,
              name: "角色删除",
              description: "删除角色",
              selected: true,
            },
          ],
        },
        {
          id: "monitor",
          name: "系统监控",
          icon: "fas fa-desktop",
          iconColor: "text-green-600",
          expanded: false,
          selected: false,
          permissions: [
            {
              id: 9,
              name: "在线用户查询",
              description: "查询在线用户",
              selected: false,
            },
            {
              id: 10,
              name: "强制退出",
              description: "强制用户下线",
              selected: false,
            },
            {
              id: 11,
              name: "服务器监控",
              description: "查看服务器状态",
              selected: false,
            },
            {
              id: 12,
              name: "缓存监控",
              description: "查看缓存状态",
              selected: false,
            },
          ],
        },
        {
          id: "log",
          name: "日志管理",
          icon: "fas fa-clipboard-list",
          iconColor: "text-purple-600",
          expanded: false,
          selected: false,
          permissions: [
            {
              id: 13,
              name: "操作日志查询",
              description: "查询操作日志",
              selected: false,
            },
            {
              id: 14,
              name: "操作日志删除",
              description: "删除操作日志",
              selected: false,
            },
            {
              id: 15,
              name: "登录日志查询",
              description: "查询登录日志",
              selected: false,
            },
            {
              id: 16,
              name: "登录日志删除",
              description: "删除登录日志",
              selected: false,
            },
          ],
        },
      ],
      // 权限配置定义
      permissionConfig: {
        system: {
          selected: true,
          modules: {
            user: [
              "query",
              "add",
              "edit",
              "remove",
              "export",
              "import",
              "resetPwd",
              "assignRole",
            ],
            role: [
              "query",
              "add",
              "edit",
              "remove",
              "export",
              "assignPermission",
            ],
            permission: ["query", "add", "edit", "remove", "export"],
            menu: ["query", "add", "edit", "remove", "sort"],
            dept: ["query", "add", "edit", "remove", "export"],
          },
        },
        monitor: {
          selected: false,
          modules: {
            online: ["query", "forceLogout", "detail"],
            job: ["query", "add", "edit", "remove", "execute", "changeStatus"],
            server: ["query", "cpu", "memory", "disk"],
            cache: ["query", "list", "clear", "stats"],
          },
        },
        log: {
          selected: false,
          modules: {
            operlog: ["query", "remove", "export", "detail", "clear", "stats"],
            loginlog: ["query", "remove", "export", "detail", "clear", "stats"],
          },
        },
        config: {
          selected: false,
          modules: {
            dict: ["query", "add", "edit", "remove", "export", "refresh"],
            param: ["query", "add", "edit", "remove", "export"],
          },
        },
        tool: {
          selected: false,
          modules: {
            build: ["create", "preview", "export", "copy"],
            gen: ["generate", "import", "edit", "sync", "preview", "download"],
            interface: [
              "query",
              "test",
              "debug",
              "doc",
              "export",
              "import",
              "monitor",
              "stats",
            ],
          },
        },
      },

      // 操作映射表
      operationMap: {
        query: { name: "查询", desc: "查询列表" },
        add: { name: "新增", desc: "新增" },
        edit: { name: "修改", desc: "修改信息" },
        remove: { name: "删除", desc: "删除" },
        export: { name: "导出", desc: "导出数据" },
        import: { name: "导入", desc: "导入数据" },
        detail: { name: "详情", desc: "查看详情" },
        assignRole: { name: "分配角色", desc: "为用户分配角色" },
        assignPermission: { name: "权限分配", desc: "为角色分配权限" },
        resetPwd: { name: "重置密码", desc: "重置用户密码" },
        sort: { name: "排序", desc: "调整排序" },
        forceLogout: { name: "强制下线", desc: "强制用户下线" },
        execute: { name: "执行", desc: "立即执行" },
        changeStatus: { name: "状态修改", desc: "修改状态" },
        cpu: { name: "CPU监控", desc: "查看CPU使用情况" },
        memory: { name: "内存监控", desc: "查看内存使用情况" },
        disk: { name: "磁盘监控", desc: "查看磁盘使用情况" },
        list: { name: "列表", desc: "查看列表" },
        clear: { name: "清理", desc: "清理数据" },
        stats: { name: "统计", desc: "查看统计信息" },
        refresh: { name: "刷新", desc: "刷新缓存" },
        create: { name: "构建", desc: "创建表单" },
        preview: { name: "预览", desc: "预览效果" },
        copy: { name: "复制", desc: "复制配置" },
        generate: { name: "生成", desc: "生成代码" },
        sync: { name: "同步", desc: "同步表结构" },
        download: { name: "下载", desc: "下载代码" },
        test: { name: "测试", desc: "测试接口功能" },
        debug: { name: "调试", desc: "调试接口参数" },
        doc: { name: "文档", desc: "查看接口文档" },
        monitor: { name: "监控", desc: "监控接口状态" },
      },

      // 模块名称映射
      moduleNames: {
        user: "用户",
        role: "角色",
        permission: "权限",
        menu: "菜单",
        dept: "部门",
        online: "在线用户",
        job: "定时任务",
        server: "服务器",
        cache: "缓存",
        operlog: "操作日志",
        loginlog: "登录日志",
        dict: "字典",
        param: "参数",
        build: "表单",
        gen: "代码",
        interface: "接口",
      },

      // 动态权限数据（初始化为空，在 created 中初始化）
      dynamicPermissions: {},
    };
  },
  computed: {
    // 计算是否有选中项
    hasSelected() {
      return this.selectedUserIds.length > 0;
    },
    // 计算选中数量
    selectedCount() {
      return this.selectedUserIds.length;
    },
    // 获取选中的用户对象数组
    selectedUsers() {
      return this.users.filter((user) =>
        this.selectedUserIds.includes(user.id)
      );
    },
    currentModuleName() {
      const module = this.permissionModules.find(
        (m) => m.id === this.selectedModule
      );
      if (module) {
        return module.name;
      }
      const submodule = this.permissionModules
        .flatMap((m) => m.children)
        .find((s) => s.id === this.selectedModule);
      return submodule ? submodule.name : "";
    },

    // 动态获取当前模块的权限点
    currentPermissions() {
      // 根据选中的模块ID返回对应的权限点数组
      if (this.selectedModule && this.dynamicPermissions[this.selectedModule]) {
        return this.dynamicPermissions[this.selectedModule];
      }
      return [];
    },

    // 获取当前选中的权限点数量
    selectedPermissionsCount() {
      return this.currentPermissions.filter((p) => p.selected).length;
    },
    // 分页计算属性，使用筛选后的用户列表
    paginatedUsers() {
      const users = this.filteredUsers;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return users.slice(start, end);
    },
    // 角色管理的分页计算属性
    paginatedRoles() {
      return this.filteredRoles;
    },
    totalPages() {
      const users = this.filteredUsers;
      return Math.ceil(users.length / this.pageSize);
    },
    // 过滤后的权限模块
    filteredPermissionModules() {
      if (!this.moduleSearchKeyword.trim()) {
        return this.permissionModules;
      }

      const keyword = this.moduleSearchKeyword.toLowerCase();
      const result = [];

      this.permissionModules.forEach((module) => {
        // 检查模块名称是否匹配
        const moduleMatch = module.name.toLowerCase().includes(keyword);

        // 检查子模块是否匹配
        const matchedChildren = module.children
          ? module.children.filter((child) =>
              child.name.toLowerCase().includes(keyword)
            )
          : [];

        // 如果模块或子模块匹配，则添加到结果中
        if (moduleMatch || matchedChildren.length > 0) {
          result.push({
            ...module,
            children: moduleMatch ? module.children : matchedChildren,
            expanded: true, // 搜索时自动展开
          });
        }
      });

      return result;
    },
  },
  mounted() {
    // 原有的其他初始化逻辑
    this.initializeFromLocalStorage();
    this.applyRoleFilters();
    this.dynamicPermissions = this.initDynamicPermissions();
    this.loadPermissionConfig();
  },
  methods: {
    selectUserFormDepartment(dept) {
      this.userForm.department = dept;
      this.showUserFormDepartmentDropdown = false;
    },
    // 添加分页方法
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        this.updateAllSelectedState();
      }
    },
    changePageSize(size) {
      this.pageSize = size;
      this.currentPage = 1; // 重置到第一页
      this.updateAllSelectedState();
    },
    toggleMenu(index) {
      this.mainMenus[index].expanded = !this.mainMenus[index].expanded;
      // 如果展开了菜单，则将其他菜单收起
      if (this.mainMenus[index].expanded) {
        this.mainMenus.forEach((menu, i) => {
          if (i !== index) {
            menu.expanded = false;
          }
        });
      }
    },
    selectSubmenu(menuIndex, submenuIndex) {
      // 重置所有菜单的激活状态
      this.mainMenus.forEach((menu) => {
        menu.active = false;
        menu.subMenus.forEach((submenu) => {
          submenu.active = false;
        });
      });
      // 设置当前选中的菜单和子菜单为激活状态
      this.mainMenus[menuIndex].active = true;
      this.mainMenus[menuIndex].subMenus[submenuIndex].active = true;
    },
    // 单选用户
    toggleSelectUser(user, event) {
      // 清除之前的选择
      this.selectedUserIds = [];
      this.users.forEach((u) => (u.selected = false));

      if (event.target.checked) {
        // 如果选中，设置为唯一选中
        this.selectedUserIds.push(user.id);
        user.selected = true;
        this.currentSelectedUser = user;
      } else {
        // 如果取消选中，清除所有选择
        this.currentSelectedUser = null;
      }
      this.updateAllSelectedState();
    },
    // 全选逻辑（改为单选模式下的特殊处理）
    toggleSelectAll() {
      if (this.isAllSelected) {
        // 取消全选
        this.selectedUserIds = [];
        this.currentSelectedUser = null; // 清除当前选中用户
        this.users.forEach((user) => {
          user.selected = false;
        });
        this.isAllSelected = false;
      } else {
        // 全选当前页（在单选模式下，这应该只选中第一个）
        if (this.paginatedUsers.length > 0) {
          const firstUser = this.paginatedUsers[0];
          this.selectedUserIds = [firstUser.id];
          firstUser.selected = true;
          this.currentSelectedUser = firstUser;

          // 确保其他用户不被选中
          this.users.forEach((user) => {
            if (user.id !== firstUser.id) {
              user.selected = false;
            }
          });
        }
        this.isAllSelected = true;
      }
    },
    // 更新全选状态
    updateAllSelectedState() {
      if (this.paginatedUsers.length === 0) {
        this.isAllSelected = false;
        return;
      }
      this.isAllSelected = this.paginatedUsers.every((user) =>
        this.selectedUserIds.includes(user.id)
      );
    },
    async batchDelete() {
      if (this.selectedUserIds.length > 0) {
        const selectedNames = this.selectedUsers
          .map((user) => user.name)
          .join(", ");

        try {
          await ElMessageBox.confirm(
            `确定要删除选中的 ${this.selectedCount} 个用户吗？\n${selectedNames}`,
            "确认删除",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          );

          this.users = this.users.filter(
            (user) => !this.selectedUserIds.includes(user.id)
          );
          this.saveUsersToLocalStorage();
          this.clearSelection();
          this.currentSelectedUser = null;
          this.applyFilters();

          if (this.paginatedUsers.length === 0 && this.currentPage > 1) {
            this.currentPage--;
          }

          ElMessage.success("用户删除成功");
        } catch (error) {
          // 用户点击取消
          
        }
      }
    },
    // 批量导出方法
    batchExport() {
      if (this.selectedUserIds.length > 0) {
        const exportData = this.selectedUsers.map((user) => ({
          name: user.name,
          username: user.username,
          phone: user.phone,
          email: user.email,
          department: user.department,
          roles: user.roles.join(", "),
          status: user.status,
          lastLogin: user.lastLogin,
        }));
        
        ElMessage.success(`已导出 ${this.selectedCount} 个用户的数据`);
      }
    },
    getRoleClass(role) {
      const classes = {
        系统管理员: "bg-red-100 text-red-800",
        部门管理员: "bg-blue-100 text-blue-800",
        普通用户: "bg-green-100 text-green-800",
        访客: "bg-gray-100 text-gray-800",
        审计员: "bg-purple-100 text-purple-800",
        安全员: "bg-yellow-100 text-yellow-800",
        运维人员: "bg-indigo-100 text-indigo-800",
        数据分析师: "bg-teal-100 text-teal-800",
      };
      return classes[role] || "bg-gray-100 text-gray-800";
    },
    editUser(user) {
      this.editingUser = true;
      this.userForm = { ...user };
      this.showAddUserModal = true;
      // 清除选择状态
      this.clearSelection();
    },
    resetPassword(user) {
      this.currentUser = user;
      this.newPassword = "";
      this.confirmPassword = "";
      this.showResetPasswordModal = true;
      // 清除选择状态
      this.clearSelection();
    },
    // 清除选择状态的方法
    clearSelection() {
      this.selectedUserIds = [];
      this.currentSelectedUser = null; //清除当前选中用户
      this.isAllSelected = false;
      this.users.forEach((user) => {
        user.selected = false;
      });
    },
    toggleUserStatus(user) {
      user.status = user.status === "启用" ? "禁用" : "启用";
      //保存到本地存储
      this.saveUsersToLocalStorage();
      // 清除选择状态
      this.clearSelection();
    },
    // 初始化本地存储数据
    initializeFromLocalStorage() {
      // 用户数据
      const storedUsers = localStorage.getItem("userManagementUsers");
      const storedNextId = localStorage.getItem("userManagementNextUserId");
      // 角色数据
      const storedRoles = localStorage.getItem("userManagementRoles");
      const storedNextRoleId = localStorage.getItem("userManagementNextRoleId");
      if (storedUsers) {
        this.users = JSON.parse(storedUsers);
      }
      if (storedNextId) {
        this.nextUserId = parseInt(storedNextId);
      }
      if (storedRoles) {
        this.roles = JSON.parse(storedRoles);
      }
      if (storedNextRoleId) {
        this.nextRoleId = parseInt(storedNextRoleId);
      }
      // 初始化筛选 - 设置 filteredUsers 为所有用户
      this.filteredUsers = [...this.users];
      // 初始化角色筛选列表
      this.filteredRoles = [...this.roles];
    },
    // 保存用户数据到本地存储
    saveUsersToLocalStorage() {
      localStorage.setItem("userManagementUsers", JSON.stringify(this.users));
      localStorage.setItem(
        "userManagementNextUserId",
        this.nextUserId.toString()
      );
    },
    // 保存角色数据到本地存储
    saveRolesToLocalStorage() {
      localStorage.setItem("userManagementRoles", JSON.stringify(this.roles));
      localStorage.setItem(
        "userManagementNextRoleId",
        this.nextRoleId.toString()
      );
    },
    // 新建用户方法
    addUser() {
      this.editingUser = false;
      this.userForm = {
        id: this.nextUserId++, // 自动生成新ID
        username: "",
        name: "",
        phone: "",
        email: "",
        department: "",
        gender: "男",
        roles: [],
        status: "启用",
        remark: "",
        password: "",
        selected: false,
        lastLogin: "从未登录", // 新用户默认从未登录
      };
      this.showAddUserModal = true;
    },
    // 修改保存用户方法
    saveUser() {
      // 验证必填字段
      if (!this.userForm.username || !this.userForm.name) {
        ElMessage.warning("请填写用户名和真实姓名");
        return;
      }

      if (this.editingUser) {
        // 编辑现有用户
        const index = this.users.findIndex(
          (user) => user.id === this.userForm.id
        );
        if (index !== -1) {
          this.users.splice(index, 1, { ...this.userForm });
        }
        ElMessage.success("用户信息更新成功");
      } else {
        // 新增用户
        const newUser = {
          ...this.userForm,
          id: this.nextUserId++,
          lastLogin: "从未登录",
        };
        this.users.unshift(newUser);
        ElMessage.success("用户创建成功");
      }

      // 保存到本地存储
      this.saveUsersToLocalStorage();
      this.showAddUserModal = false;
      this.resetUserForm();
      // 重置到第一页以显示新用户
      this.currentPage = 1;
      this.applyFilters();
    },
    // 添加重置用户表单方法
    resetUserForm() {
      this.userForm = {
        username: "",
        name: "",
        phone: "",
        email: "",
        department: "",
        gender: "男",
        roles: [],
        status: "启用",
        remark: "",
        password: "",
      };
      this.editingUser = false;
    },
    // 切换部门下拉菜单
    toggleDepartmentDropdown() {
      this.showDepartmentDropdown = !this.showDepartmentDropdown;
      // 关闭其他下拉菜单
      if (this.showDepartmentDropdown) {
        this.showRoleDropdown = false;
        this.showStatusDropdown = false;
      }
    },
    // 切换角色下拉菜单
    toggleRoleDropdown() {
      this.showRoleDropdown = !this.showRoleDropdown;
      // 关闭其他下拉菜单
      if (this.showRoleDropdown) {
        this.showDepartmentDropdown = false;
        this.showStatusDropdown = false;
      }
    },
    // 切换状态下拉菜单
    toggleStatusDropdown() {
      this.showStatusDropdown = !this.showStatusDropdown;
      // 关闭其他下拉菜单
      if (this.showStatusDropdown) {
        this.showDepartmentDropdown = false;
        this.showRoleDropdown = false;
      }
    },
    // 添加选择部门方法
    selectDepartment(dept) {
      this.filterConditions.department = dept;
      this.showDepartmentDropdown = false;
      this.applyFilters(); // 确保调用筛选
    },
    selectRole(role) {
      this.filterConditions.role = role;
      this.showRoleDropdown = false;
      this.applyFilters();
    },
    selectStatus(status) {
      this.filterConditions.status = status;
      this.showStatusDropdown = false;
      this.applyFilters();
    },
    handleSearch() {
      this.applyFilters();
    },
    // 应用筛选条件
    applyFilters() {
      let filteredUsers = [...this.users];
      // 部门筛选-- 当有数据时才继续筛选
      if (this.filterConditions.department !== "全部部门") {
        filteredUsers = filteredUsers.filter(
          (user) => user.department === this.filterConditions.department
        );
      }
      // 角色筛选-- 在已有筛选结果上继续筛选
      if (this.filterConditions.role !== "全部角色") {
        filteredUsers = filteredUsers.filter((user) =>
          user.roles.includes(this.filterConditions.role)
        );
      }
      // 状态筛选-- 在已有筛选结果上继续筛选
      if (this.filterConditions.status !== "全部状态") {
        filteredUsers = filteredUsers.filter(
          (user) => user.status === this.filterConditions.status
        );
      }
      // 搜索筛选 -- 在已有筛选结果上继续筛选
      if (this.filterConditions.search && filteredUsers.length > 0) {
        const searchTerm = this.filterConditions.search.toLowerCase();
        filteredUsers = filteredUsers.filter(
          (user) =>
            user.username.toLowerCase().includes(searchTerm) ||
            user.name.toLowerCase().includes(searchTerm) ||
            user.phone.includes(searchTerm)
        );
      }
      
      // 更新显示的用户列表
      this.filteredUsers = filteredUsers;
      this.currentPage = 1; // 重置到第一页
      this.clearSelection(); // 重置选择状态
    },

    // 点击外部关闭下拉菜单
    closeDropdowns() {
      this.showDepartmentDropdown = false;
      this.showRoleDropdown = false;
      this.showStatusDropdown = false;
    },
    toggleRole(role) {
      const index = this.userForm.roles.indexOf(role);
      if (index === -1) {
        this.userForm.roles.push(role);
      } else {
        this.userForm.roles.splice(index, 1);
      }
    },
    editRole(role) {
      this.editingRole = true;
      this.currentRole = { ...role };
      this.roleForm = {
        name: role.name,
        key: role.key,
        description: role.description,
        sort: 0,
      };
      this.showAddRoleModal = true;
    },
    configPermission(role) {
      this.currentRole = role;
      this.showPermissionModal = true;
    },
    deleteRole(role) {
      this.currentRole = role;
      this.showDeleteRoleModal = true;
    },
    // 新建角色方法
    addRole() {
      this.editingRole = false;
      this.roleForm = {
        name: "",
        key: "",
        description: "",
        sort: 0,
      };
      this.showAddRoleModal = true;
    },
    // 角色搜索处理
    handleRoleSearch() {
      this.applyRoleFilters();
    },

    // 应用角色筛选条件
    applyRoleFilters() {
      let filteredRoles = [...this.roles];
      // 搜索筛选
      if (this.roleFilterConditions.search) {
        const searchTerm = this.roleFilterConditions.search.toLowerCase();
        filteredRoles = filteredRoles.filter(
          (role) =>
            role.name.toLowerCase().includes(searchTerm) ||
            role.key.toLowerCase().includes(searchTerm) ||
            role.description.toLowerCase().includes(searchTerm)
        );
      }
      // 更新显示的角色列表
      this.filteredRoles = filteredRoles;
    },
    //保存角色方法
    saveRole() {
      // 验证必填字段
      if (!this.roleForm.name || !this.roleForm.key) {
        ElMessage.warning("请填写角色名称和角色标识");
        return;
      }

      if (this.editingRole) {
        // 编辑现有角色
        const index = this.roles.findIndex(
          (role) => role.id === this.currentRole.id
        );
        if (index !== -1) {
          this.roles.splice(index, 1, {
            ...this.currentRole,
            name: this.roleForm.name,
            key: this.roleForm.key,
            description: this.roleForm.description,
          });
        }
        ElMessage.success("角色信息更新成功");
      } else {
        // 新增角色
        const newRole = {
          id: this.nextRoleId++,
          name: this.roleForm.name,
          key: this.roleForm.key,
          description: this.roleForm.description,
          createTime: new Date()
            .toLocaleString("zh-CN", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit",
              second: "2-digit",
              hour12: false,
            })
            .replace(/\//g, "-"),
          userCount: 0,
          icon: "fas fa-user-tag",
          iconBg: "bg-gray-100",
          iconColor: "text-gray-600",
        };
        this.roles.unshift(newRole);
        ElMessage.success("角色创建成功");
      }

      // 保存到本地存储
      this.saveRolesToLocalStorage();
      this.showAddRoleModal = false;
      //立即更新角色列表显示
      this.applyRoleFilters();
      this.resetRoleForm();
    },
    // 在删除角色后重新应用筛选
    confirmDeleteRole() {
  const roleName = this.currentRole.name;
  this.roles = this.roles.filter((role) => role.id !== this.currentRole.id);
  this.saveRolesToLocalStorage();
  this.showDeleteRoleModal = false;
  this.currentRole = {};
  ElMessage.success(`角色 "${roleName}" 已删除`);
  // 重新应用筛选条件
  this.applyRoleFilters();
},
    // 添加重置角色表单方法
    resetRoleForm() {
      this.roleForm = {
        name: "",
        key: "",
        description: "",
        sort: 0,
      };
      this.editingRole = false;
      this.currentRole = {};
    },
    confirmResetPassword() {
      // 发送请求重置密码
      this.showResetPasswordModal = false;
    },
    selectModule(moduleId) {
      this.selectedModule = moduleId;
      // 根据选中的模块加载对应的权限点
      
      // 加载该模块的保存配置
      this.loadPermissionConfig();
    },
    toggleModule(moduleId) {
      const module = this.permissionModules.find((m) => m.id === moduleId);
      if (module) {
        // 只切换展开状态，不自动选择子模块
        module.expanded = !module.expanded;
      }
    },
    selectAllPermissions() {
      this.currentPermissions.forEach((permission) => {
        permission.selected = true;
      });
    },
    deselectAllPermissions() {
      this.currentPermissions.forEach((permission) => {
        permission.selected = false;
      });
    },
    togglePermissionModule(index) {
      this.permissionTree[index].expanded =
        !this.permissionTree[index].expanded;
    },
    selectModulePermissions(index) {
      const selected = this.permissionTree[index].selected;
      this.permissionTree[index].permissions.forEach((permission) => {
        permission.selected = selected;
      });
    },
    updateModuleSelection(index) {
      const allSelected = this.permissionTree[index].permissions.every(
        (p) => p.selected
      );
      const someSelected = this.permissionTree[index].permissions.some(
        (p) => p.selected
      );
      this.permissionTree[index].selected = allSelected;
      // 在实际应用中，可能需要处理"部分选中"状态
    },
    expandAllModules() {
      this.permissionTree.forEach((module) => {
        module.expanded = true;
      });
    },
    collapseAllModules() {
      this.permissionTree.forEach((module) => {
        module.expanded = false;
      });
    },
    savePermissions() {
      // 发送请求保存权限配置
      this.showPermissionModal = false;
    },
    // 重置权限配置
    resetPermissions() {
      // 重置当前模块的所有权限点为未选中状态
      this.currentPermissions.forEach((permission) => {
        permission.selected = false;
      });
      
    },
    // 保存权限配置
    savePermissionConfig() {
      // 获取当前选中的权限点
      const selectedPermissions = this.currentPermissions.filter(
        (p) => p.selected
      );

      // 保存到本地存储
      const permissionConfig =
        JSON.parse(localStorage.getItem("userManagementPermissionConfig")) ||
        {};
      permissionConfig[this.selectedModule] = {
        moduleName: this.currentModuleName,
        permissions: this.currentPermissions.map((p) => ({
          id: p.id,
          name: p.name,
          key: p.key,
          selected: p.selected,
        })),
        lastUpdate: new Date()
          .toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            hour12: false,
          })
          .replace(/\//g, "-"),
      };

      localStorage.setItem(
        "userManagementPermissionConfig",
        JSON.stringify(permissionConfig)
      );

      // 同时更新动态权限数据，确保数据同步
      this.dynamicPermissions[this.selectedModule] = [
        ...this.currentPermissions,
      ];

      

      ElMessage.success(`已保存 ${selectedPermissions.length} 个权限点的配置`);
    },

    // 从本地存储加载权限配置
    loadPermissionConfig() {
      const permissionConfig =
        JSON.parse(localStorage.getItem("userManagementPermissionConfig")) ||
        {};

      if (permissionConfig[this.selectedModule]) {
        const savedConfig = permissionConfig[this.selectedModule];
        // 更新动态权限数据
        this.dynamicPermissions[this.selectedModule] = savedConfig.permissions;
        
      } else {
        // 如果没有保存的配置，使用默认配置
        
      }
    },

    // 从本地存储加载权限配置
    loadPermissionConfig() {
      const permissionConfig =
        JSON.parse(localStorage.getItem("userManagementPermissionConfig")) ||
        {};

      if (permissionConfig[this.selectedModule]) {
        const savedConfig = permissionConfig[this.selectedModule];
        // 更新动态权限数据
        this.dynamicPermissions[this.selectedModule] = savedConfig.permissions;
        
      } else {
        // 如果没有保存的配置，使用默认配置
        
      }
    },
    // 初始化动态权限数据
    initDynamicPermissions() {
      const permissions = {};
      let idCounter = 1;

      Object.entries(this.permissionConfig).forEach(([category, config]) => {
        Object.entries(config.modules).forEach(([moduleKey, operations]) => {
          permissions[moduleKey] = operations.map((operation) => {
            const opConfig = this.operationMap[operation];
            const moduleName = this.moduleNames[moduleKey];
            return {
              id: idCounter++,
              name: `${moduleName}${opConfig.name}`,
              key: `${category}:${moduleKey}:${operation}`,
              description: opConfig.desc,
              selected: config.selected,
            };
          });
        });
      });

      return permissions;
    },
  },
  created() {
    this.initializeFromLocalStorage();
    this.applyRoleFilters();
    // 初始化权限数据
    this.dynamicPermissions = this.initDynamicPermissions();
    this.loadPermissionConfig();
  },
};
</script>
<style scoped>
/* 隐藏input number的箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}

/* 自定义滚动条 */
.permission-tree {
  max-height: 500px;
  overflow-y: auto;
}

.permission-tree::-webkit-scrollbar {
  width: 6px;
}

.permission-tree::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.permission-tree::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.permission-tree::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 子模块展开动画 */
.module-children-enter-active,
.module-children-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.module-children-enter-from,
.module-children-leave-to {
  max-height: 0;
  opacity: 0;
}

.module-children-enter-to,
.module-children-leave-from {
  max-height: 500px;
  opacity: 1;
}

/* 自定义颜色类 */
.bg-teal-100 {
  background-color: #b2f5ea;
}

.text-teal-600 {
  color: #319795;
}

.text-teal-800 {
  color: #285e61;
}

.bg-indigo-100 {
  background-color: #e5edff;
}

.text-indigo-600 {
  color: #5a67d8;
}

.text-indigo-800 {
  color: #434190;
}
</style>
